package com.sale.plugins;

import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SpringContextLoader;
import com.apache.exception.BusinessException;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.ius.plugin.UtilPlugin;
import com.apache.tools.DataMap;
import com.apache.tools.DateUtils;
import com.apache.tools.NumberUtils;
import com.apache.tools.StrUtil;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InitGoodsForSalePluginImpl implements CustomMethodPlugin {
    private Logger log = Logger.getLogger(getClass());

    @SuppressWarnings("rawtypes")
    @Override
    public Object beforeInvoke(Map<String, Object> param) {
//        ProxyManager netProxyManager = (ProxyManager) SpringContextLoader
//                .getBean("iusProxyManager");
//        ParamsVo params = new ParamsVo();
//        params.setParams("doCode", "dymicSql");
//        params.setParams("sqlKeyId", "ByObjInfo");
//        params.setKey("publicForSql");
//        params.setParams("resultType", "list");
        StringBuffer execSql = new StringBuffer();
        String saleId = String.valueOf(param.get("trsSale.w_saleId"));

        if (Validator.isNotNull(saleId)) {

            execSql.append(
                    "select t.user_id,sum(t.nums)as nums,max(t.pro_id) as pro_id,max(t.pro_no) as pro_no, ");
            execSql.append(
                    "max(t.pro_name) as pro_name,max(t.price) as price,max(t.user_owner) as user_owner,max(t.user_cname) as user_cname ");
            execSql.append(
                    "from trs_numbers t where  t.is_select='T' and t.is_pay='T' and t.sale_id='"
                            + saleId + "' group by t.user_id,t.sale_id ");
            execSql.append("having sum(nums)>0 ");
            //封装参数
//            params.setParams("dyncSql", execSql.toString());

//            ResultEntity dymicSqlParamResult = (ResultEntity) netProxyManager.doInvoke(params);
//            List<DataMap> list = (List<DataMap>)UtilPlugin.getInstance().selectObjectForDatasource(execSql.toString(),"sale");
            List<DataMap> list =  (List<DataMap>) IusPluginUtil.getInstance().select(execSql.toString(),0,0);;

//            List<DataMap> list = (List) dymicSqlParamResult.getEntity();
            if (list != null && list.size() > 0) {
                for (DataMap dataMap : list) {
                    String proId = String.valueOf(dataMap.get("proId"));
                    String proName = String.valueOf(dataMap.get("proName"));
                    String proNo = String.valueOf(dataMap.get("proNo"));
                    long numsLong = Math.round(Double.parseDouble(String.valueOf(dataMap.get("nums"))));
                    long totalNum = numsLong;//总持仓量
                    long useNum = numsLong;//可用数量
//                    String totalNum = String.valueOf(dataMap.get("nums"));//总持仓量
//                    String useNum = String.valueOf(dataMap.get("nums"));//可用数量
                    String forzenNum = String.valueOf(0);//冻结数量
                    String costPrice = String.valueOf(dataMap.get("price"));//成本价 --单价
                    Double buyPrice =
                            Double.valueOf(totalNum) * Double.valueOf(costPrice);//买入成本 --总价
                    String userId = String.valueOf(dataMap.get("userId"));
                    String userEname = String.valueOf(dataMap.get("userOwner"));
                    String userCname = String.valueOf(dataMap.get("userCname"));
                    //判断之前该用户是否拥有仓位，如果有则更新仓位；如果没有则增加仓位；
//                    ParamsVo goodsParams = new ParamsVo();
//                    goodsParams.setParams("doCode", "dymicSql");
//                    goodsParams.setParams("sqlKeyId", "ByObjInfo");
//                    goodsParams.setKey("publicForSql");
//                    goodsParams.setParams("resultType", "list");
                    StringBuffer goodsParamsSql = new StringBuffer();
                    goodsParamsSql.append("select * from trs_goods t where t.user_id='" + userId
                            + "' and t.pro_id='" + proId + "'");
//                    goodsParams.setParams("dyncSql", goodsParamsSql.toString());
//                    ResultEntity goodsResult = (ResultEntity) netProxyManager.doInvoke(goodsParams);
//                    List<DataMap> goodsList = (List) goodsResult.getEntity();
                    List<DataMap> goodsList = (List<DataMap>)UtilPlugin.getInstance().selectObjectForDatasource(goodsParamsSql.toString(),"sale");


                    if (goodsList != null && goodsList.size() > 0) {
                        //如果之前有持仓，证明该商品不是第一次发售。需要将本次发售的价格以及中签数量与之前的持仓量进行组合重新计算。

                        for (DataMap goodsMap : goodsList) {
//                            long goodsUseNum = Long.valueOf(
//                                    StrUtil.doNull(String.valueOf(goodsMap.get("useNum")), "0"));
//                            long goodsTotalNum = Long.valueOf(
//                                    StrUtil.doNull(String.valueOf(goodsMap.get("totalNum")), "0"));

                            long goodsUseNum = Math.round(Double.valueOf(
                                    StrUtil.doNull(String.valueOf(goodsMap.get("useNum")), "0")));
                            long goodsTotalNum = Math.round(Double.valueOf(
                                    StrUtil.doNull(String.valueOf(goodsMap.get("totalNum")), "0")));

                            Double goodsBuyPrice = Double.valueOf(
                                    StrUtil.doNull(String.valueOf(goodsMap.get("buyPrice")), "0"));
                            //Double goodsCostPrice = Double.valueOf(StrUtil.doNull(String.valueOf(goodsMap.get("costPrice")),
                            //		"0"));
                            Double goodsCostPrice = NumberUtils
                                    .divide(Double.valueOf(buyPrice) + goodsBuyPrice,
                                            Long.valueOf(totalNum) + goodsTotalNum, 2);//获取最新单价

//                            ParamsVo updateParams = new ParamsVo();
//                            updateParams.setParams("doCode", "dymicSql");
//                            updateParams.setKey("publicForSql");
//                            updateParams.setParams("sqlKeyId", "ByDymicSql");
//                            updateParams.setParams("resultType", "processSql");
//                            updateParams.setParams("modelTypes", "u_trsGoods");

//                            updateParams.setParams("trsGoods.w_proId", proId);
//                            updateParams.setParams("trsGoods.w_userId", userId);
//
//                            updateParams.setParams("trsGoods.totalNum",
//                                    Long.valueOf(totalNum) + goodsTotalNum);
//                            updateParams.setParams("trsGoods.useNum",
//                                    Long.valueOf(useNum) + goodsUseNum);
//                            updateParams.setParams("trsGoods.costPrice", goodsCostPrice);
//                            updateParams.setParams("trsGoods.buyPrice",
//                                    Double.valueOf(buyPrice) + goodsBuyPrice);
//
//                            updateParams.setParams("trsGoods.modifyTime",
//                                    DateUtils.Now.fmt_yyyyMMdd_HHmmss());
//                            updateParams.setParams("trsGoods.modifyUser", "sys");
//                            netProxyManager.doInvoke(updateParams);

                            Map<String, Object> paramsMap = new HashMap<String, Object>();

                            paramsMap.put("trsGoods.w_proId", proId);
                            paramsMap.put("trsGoods.w_userId", userId);

                            paramsMap.put("trsGoods.totalNum",
                                    Long.valueOf(totalNum) + goodsTotalNum);
                            paramsMap.put("trsGoods.useNum",
                                    Long.valueOf(useNum) + goodsUseNum);
                            paramsMap.put("trsGoods.costPrice", goodsCostPrice);
                            paramsMap.put("trsGoods.buyPrice",
                                    Double.valueOf(buyPrice) + goodsBuyPrice);

                            paramsMap.put("trsGoods.modifyTime",
                                    DateUtils.Now.fmt_yyyyMMdd_HHmmss());
                            paramsMap.put("trsGoods.modifyUser", "sys");
                           UtilPlugin.getInstance().saveByParams("sale","u_trsGoods",paramsMap);

                        }

                    } else {
//                        ParamsVo insertParams = new ParamsVo();
//                        insertParams.setParams("doCode", "dymicSql");
//                        insertParams.setKey("publicForSql");
//                        insertParams.setParams("sqlKeyId", "ByDymicSql");
//                        insertParams.setParams("resultType", "processSql");
//
//                        insertParams.setParams("modelTypes", "i_trsGoods");
//                        insertParams.setParams("trsGoods.proId", proId);
//                        insertParams.setParams("trsGoods.proName", proName);
//                        insertParams.setParams("trsGoods.proNo", proNo);
//                        insertParams.setParams("trsGoods.totalNum", totalNum);
//                        insertParams.setParams("trsGoods.useNum", useNum);
//                        insertParams.setParams("trsGoods.forzenNum", forzenNum);
//                        insertParams.setParams("trsGoods.costPrice", costPrice);
//                        insertParams.setParams("trsGoods.buyPrice", buyPrice);
//                        insertParams.setParams("trsGoods.userId", userId);
//                        insertParams.setParams("trsGoods.userEname", userEname);
//                        insertParams.setParams("trsGoods.userCname", userCname);
//                        insertParams.setParams("trsGoods.createTime",
//                                DateUtils.Now.fmt_yyyyMMdd_HHmmss());
//                        insertParams.setParams("trsGoods.delStatus", "F");
//                        insertParams.setParams("trsGoods.createUser", "sys");
//                        netProxyManager.doInvoke(insertParams);
                        Map<String, Object> paramsMap = new HashMap<String, Object>();
                        paramsMap.put("trsGoods.proId", proId);
                        paramsMap.put("trsGoods.proName", proName);
                        paramsMap.put("trsGoods.proNo", proNo);
                        paramsMap.put("trsGoods.totalNum", totalNum);
                        paramsMap.put("trsGoods.useNum", useNum);
                        paramsMap.put("trsGoods.forzenNum", forzenNum);
                        paramsMap.put("trsGoods.costPrice", costPrice);
                        paramsMap.put("trsGoods.buyPrice", buyPrice);
                        paramsMap.put("trsGoods.userId", userId);
                        paramsMap.put("trsGoods.userEname", userEname);
                        paramsMap.put("trsGoods.userCname", userCname);
                        paramsMap.put("trsGoods.createTime",
                                DateUtils.Now.fmt_yyyyMMdd_HHmmss());
                        paramsMap.put("trsGoods.delStatus", "F");
                        paramsMap.put("trsGoods.createUser", "sys");
                        UtilPlugin.getInstance().saveByParams("sale","i_trsGoods",paramsMap);


                    }

                }
            } else {
                log.info("未找到汇总的可以初始化持仓的数据，请检查！！！！！");
                throw new BusinessException("!!!!!!!!!!!!!!!！");
            }
        }
        return null;
    }

    @Override
    public Object doInvoke(Map<String, Object> param) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Object afterInvoke(Map<String, Object> param) {

        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 规则校验入口（专门给系统公式规则提供的）
     *
     * @param paramsVo
     */
    public void run(ParamsVo paramsVo) {
        beforeInvoke(paramsVo.getParams());
    }
}
